package com.spring.cootask.web.service.impl;


import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.google.common.collect.Maps;

import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.oa.api.web.dao.OaMapper;
import com.spera.shopoa.util.ShopOaSessionUtil;
import com.spring.cootask.web.dao.FeTaskMapper;
import com.spring.cootask.web.dao.FeTaskUserMapper;
import com.spring.cootask.web.dao.FeTaskUserTableMapper;
import com.spring.cootask.web.model.CooTaskUserTableWithBLOBs;
import com.spring.cootask.web.model.FeTask;
import com.spring.cootask.web.model.FeTaskUser;
import com.spring.cootask.web.model.FeTaskUserTable;
import com.spring.cootask.web.model.FeTaskUserTableByBase;
import com.spring.cootask.web.model.FeTaskUserWithBLOBs;
import com.spring.cootask.web.service.TaskTransService;
import com.spring.security.core.util.ApplicationUtils;
import com.spring.security.web.model.BaseResult;
import com.spring.tools.MyTools;
import com.spring.tools.XmlUtils;

@Service
public class TaskTransServiceImpl implements TaskTransService{

    @Resource
    private FeTaskUserTableMapper feTaskUserTableMapper;
    
    @Resource
    private FeTaskUserMapper feTaskUserMapper;
    
    @Resource
    private OaMapper oaMapper;
    
    @Resource
    private FeTaskMapper feTaskMapper;

	//private FeTaskUser feTaskUser;    

	@Override
	public List<FeTaskUserTable> feTaskUserTable(String taskUserID,String table_type) {
		HashMap<String,Object> m = Maps.newHashMap();
		m.put("taskUserID",taskUserID);
		m.put("table_type",table_type);
		return feTaskUserTableMapper.selectByTaskUserID(m);
	}
	
	
	
	@Override
	public FeTaskUserWithBLOBs feTaskUser(String feTaskUserID) {
		return feTaskUserMapper.selectByPrimaryKey(feTaskUserID);
	}
	
	@Override
	public BaseResult feTaskUser(FeTaskUserWithBLOBs feTaskUserWithBLOBs) throws Exception {
		
		List<Map<String, Object>> list=feTaskUserWithBLOBs.getPlanData();
		if(list!=null){
			String jsonStr = JSON.toJSONString(list);
			String xmlStr = XmlUtils.list2xmlBody(list, "root");
			
			feTaskUserWithBLOBs.setPlanDataJson(jsonStr);
			feTaskUserWithBLOBs.setPlanDataXml(xmlStr);
			feTaskUserWithBLOBs.setUserDataJson(jsonStr);
			feTaskUserWithBLOBs.setUserDataXml(xmlStr);
		}
		List<Map<String, Object>> list2=feTaskUserWithBLOBs.getUserData();
		if(list2!=null){
			String jsonStr = JSON.toJSONString(list2);
			String xmlStr = XmlUtils.list2xmlBody(list2, "root");
			
			feTaskUserWithBLOBs.setUserDataJson(jsonStr);
			feTaskUserWithBLOBs.setUserDataXml(xmlStr);
			//System.out.println(jsonStr);
			//System.out.println(xmlStr);
		}		
		int effect=feTaskUserMapper.updateByPrimaryKeySelective(feTaskUserWithBLOBs);
		
		return MyTools.checkResult(effect);
	}
	
	@Override
	public List<Map<String, Object>> easyTreeDeptUser(String taskID, String dept_id) {
		Map<String,Object> sp = new HashMap<String,Object>();
		sp.put("dept_id", dept_id);
		List<Map<String, Object>> m = oaMapper.queryDepartmentParkAll(sp);
		List<Map<String, Object>> parm = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> cList = Lists.newArrayList();
		for(Map<String, Object> model:m){
			parm.add(model);
			cList.add(model);
		}	
		List<FeTaskUserWithBLOBs> user = feTaskUserMapper.selectByTaskID(taskID);
		
		getDeptUserChildrenByPid(cList,parm,user);
		return  cList;
	}
	/**
	 * 閫掑綊鏌ュ嚭閮ㄩ棬鐖惰妭鐐圭殑鐢ㄦ埛鍙婂瓙閮ㄩ棬鑺傜偣
	 * @param m
	 */
	private void getDeptUserChildrenByPid(List<Map<String, Object>> cList,List<Map<String, Object>> m,List<FeTaskUserWithBLOBs> user){
		Map<String,Object> parm = new HashMap<String,Object>();
		String dept_id = "";
		for(Map<String, Object> model:m){
			dept_id = ApplicationUtils.Object2String(model.get("id"));
			if(ApplicationUtils.isNotNull(dept_id)){
				parm.put("dept_id", dept_id);
				//鑾峰彇閮ㄩ棬浜哄憳
				List<Map<String, Object>> users =  oaMapper.queryUserByDeptId(parm);
				for(Map<String, Object> ru:users){
					boolean temp=false;
					for(FeTaskUserWithBLOBs u:user){
						if(u.getUserId().equals(String.valueOf(ru.get("id")))){
							ru.put("hasTrans", 1);
							ru.put("taskUserID", u.getId());
							temp=true;
						}
					}
					if(!temp){
						ru.put("checked", 0);
						ru.put("taskUserID", null);
					}
					
					cList.add(ru);
				}
				//鑾峰彇涓嬬骇閮ㄩ棬
				List<Map<String, Object>> cm = oaMapper.queryDepartmentParkChildrenAll(parm);
				for(Map<String, Object> rd:cm){
					cList.add(rd);
				}
				if(cm!=null&&cm.size()>0){
					//model.put("children",cList);
					getDeptUserChildrenByPid(cList,cm,user);
				}
			}
		}
	}
	
	
	@Override
	public BaseResult feTaskUserTableByBase(FeTaskUserTableByBase feTaskUserTableByBase) throws Exception  {
		
		List<FeTaskUserWithBLOBs> FeTaskUsers=feTaskUserTableByBase.getFeTaskUsers();
		
		ArrayList<String> toDeleteTaskUserIDs=new ArrayList<String>();
			
		int sort=0;
		
		for(FeTaskUserWithBLOBs feTaskUser:FeTaskUsers){
			
			HashMap<String,Object> param=new HashMap<String,Object>();
			param.put("userID", feTaskUser.getUserId());
			param.put("taskID", feTaskUserTableByBase.getTaskID());
			param.put("tablebaseID", feTaskUserTableByBase.getTablebaseID());
			
			List<FeTaskUserWithBLOBs> list=feTaskUserMapper.selectByTaskAndUserID(param);

			if(list.size()!=0){				
				for(FeTaskUserWithBLOBs feTaskUserWithBLOBs:list){	
					
					toDeleteTaskUserIDs.add(feTaskUserWithBLOBs.getId());
				}
			}else{
				if(feTaskUser.getDatatype()!=null&&feTaskUser.getDatatype().equals("d")){
					continue;
				}
				feTaskUser.setFeTaskid(feTaskUserTableByBase.getTaskID());
				
				String id=UUID.randomUUID().toString();
				feTaskUser.setId(id);
				feTaskUser.setSort(sort);				
				sort++;
				
				int effect=feTaskUserMapper.insert(feTaskUser);
				if(effect==0){
					throw new Exception();
				}	
				toDeleteTaskUserIDs.add(id);
			}	
		}
		//删除原有字段 toDeleteTaskUserIDs
		feTaskUserTableMapper.deleteByTaskUserID(toDeleteTaskUserIDs);
		
		feTaskUserTableByBase.setTaskUserIDs(toDeleteTaskUserIDs);
		feTaskUserTableMapper.insert(feTaskUserTableByBase);
		
		return new BaseResult("1","操作成功");
	}

	@Override
	public List<FeTask> trans(String taskID) {
		FeTask feTask=new FeTask();
		feTask.setPid(taskID);
		FeTask parentTask= feTaskMapper.selectByPrimaryKey(taskID);
		List<FeTask> list = new ArrayList<FeTask>();
		list.add(parentTask);
		//List<FeTask> listc= feTaskMapper.selectTaskTransByPid(feTask);
		for(FeTask feTask1:list){
			getTransChildren(feTask1);			
		}
		return list;
	}
	
	private void getTransChildren(FeTask feTask){
		FeTask feTask1=new FeTask();
		feTask1.setPid(feTask.getId());
		List<FeTask> list= feTaskMapper.selectTaskTransByPid(feTask1);
		
		for(FeTask feTask2:list){
			feTask.getChildren().add(feTask2);
			getTransChildren(feTask2);
		}
	}
	
	@Override
	public List<FeTaskUserWithBLOBs> transDetail(String taskID) {
		return feTaskUserMapper.selectByTaskID(taskID);
	}

    
    @Override
    public BaseResult saveFormData(ShopOaSessionUtil.OaUser oaUser, List<Map<String, Object>> jsonData)
     throws Exception{
        BaseResult ret = new BaseResult();
        if(oaUser==null||!ApplicationUtils.isNotNull(oaUser.getOa_user_id())){
            ret.setStatus("0");
            ret.setMsg("请先登录");
            return ret;
        }
        String jsonStr = "";
        String xmlStr = "";
        if(jsonData!=null&&jsonData.size()>0) {
            Map<String, Object> jsonM = jsonData.get(0);
            String id = ApplicationUtils.Object2String(jsonM.get("taskUserId"));
            if (ApplicationUtils.isNotNull(id)) {
                //解析成json
                jsonStr = JSON.toJSONString(jsonData);
                //解析成xml
                xmlStr = XmlUtils.list2xmlBody(jsonData, "root");
               // xmlStr = XmlUtils.map2xmlBody(jsonData.get(0), "root");
                FeTaskUserWithBLOBs model = new FeTaskUserWithBLOBs();
                model.setId(id);
                model.setChangedtime(new Date());
                model.setOperatorid(oaUser.getOa_user_id());
                model.setOperatorname(oaUser.getOa_user_name());
                model.setPlanDataJson(jsonStr);
                model.setPlanDataXml(xmlStr);
                
                feTaskUserMapper.updateByPrimaryKeySelective(model);
            }else{
                ret.setStatus("0");
                ret.setMsg("主键不可为空");
            }
        }else{
            ret.setStatus("0");
            ret.setMsg("内容不可为空");
        }
        return ret;
    }
    
    @Override
	public BaseResult updateTaskUser(FeTaskUserWithBLOBs feTaskUser) throws Exception{
    	int effect=feTaskUserMapper.updateByPrimaryKeySelective(feTaskUser);
    	return MyTools.checkResult(effect);
    }

}
